from flask import request, jsonify, session
from pymongo import MongoClient
from werkzeug.security import generate_password_hash, check_password_hash
import logging
from bson.objectid import ObjectId

# 假设使用 MongoDB 存储历史记录
client_his = MongoClient('mongodb://localhost:27017/')
db_his = client_his['chat_history']
history_collection = db_his['conversations']

# MongoDB 用户数据库配置
client_user = MongoClient('mongodb://localhost:27017/')
db_user = client_user['user_database']
user_collection = db_user['users']

# 注册接口
def register():
    data = request.get_json()
    if not data:
        logging.error('请求数据为空或格式错误')
        return jsonify({'message': '请求数据为空或格式错误'}), 400

    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        logging.info('注册失败：用户名和密码不能为空')
        return jsonify({'message': '用户名和密码不能为空'}), 400

    try:
        logging.info('检查用户名是否已存在')
        if user_collection.find_one({'username': username}):
            logging.info(f'注册失败：用户名 {username} 已存在')
            return jsonify({'message': '用户名已存在'}), 400

        # 加密密码
        hashed_password = generate_password_hash(password)

        # 插入新用户
        logging.info(f'插入新用户 {username}')
        user_collection.insert_one({'username': username, 'password': hashed_password})
        logging.info(f'用户 {username} 注册成功')
        return jsonify({'message': '注册成功'}), 201

    except Exception as e:
        logging.error(f'注册过程中出现未知错误: {str(e)}')
        return jsonify({'message': f'注册失败: {str(e)}'}), 500


# 登录接口
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    if not username or not password:
        logging.info('登录失败：用户名和密码不能为空')
        return jsonify({'message': '用户名和密码不能为空'}), 400

    try:
        logging.info(f'尝试查找用户: {username}')
        user = user_collection.find_one({'username': username})
        if user:
            logging.info('找到用户，开始验证密码')
        else:
            logging.info('未找到用户')

        if user and check_password_hash(user['password'], password):
            session['user_id'] = str(user['_id'])
            session['username'] = username
            logging.info('登录成功')
            return jsonify({'message': '登录成功', 'username': username}), 200
        else:
            logging.info('登录失败：用户名或密码错误')
            return jsonify({'message': '用户名或密码错误'}), 401

    except Exception as e:
        logging.error(f'登录失败: {str(e)}')
        return jsonify({'message': f'登录失败: {str(e)}'}), 500
    
# 检查登录状态接口
def check_login():
    if 'user_id' in session:
        return jsonify({'isLoggedIn': True, 'username': session.get('username')}), 200
    else:
        return jsonify({'isLoggedIn': False}), 200

# 注销接口
def logout():
    try:
        if 'user_id' in session:
            # 清除会话信息
            session.pop('user_id', None)
            logging.info('用户注销成功')
            return jsonify({'message': '注销成功'}), 200
        else:
            logging.info('用户未登录，无需注销')
            return jsonify({'message': '用户未登录'}), 401
    except Exception as e:
        logging.error(f'注销失败: {str(e)}')
        return jsonify({'message': f'注销失败: {str(e)}'}), 500



# 获取用户聊天历史记录接口
def get_history():
    if 'user_id' not in session:
        logging.info('用户未登录，无法获取历史记录')
        return jsonify({'message': '用户未登录'}), 401
    user_id = session['user_id']
    try:
        # 转换 user_id 为 ObjectId 类型
        user_id_obj = ObjectId(user_id)
        logging.info(f'开始为用户 {user_id} 查询历史记录')
        history = list(history_collection.find({'user_id': user_id_obj}, {'_id': 1, 'messages': 1}))
        logging.info(f'查询到 {len(history)} 条历史记录')
        conversations = []
        for record in history:
            record['id'] = str(record.pop('_id'))
            conversations.append(record)
        return jsonify({'conversations': conversations}), 200
    except Exception as e:
        logging.error(f'获取历史记录失败: {str(e)}')
        return jsonify({'message': f'获取历史记录失败: {str(e)}'}), 500
    

# 保存或更新历史记录接口
def update_history():
    if 'user_id' not in session:
        return jsonify({'message': '用户未登录'}), 401
    user_id = session['user_id']
    data = request.get_json()
    conversation_id = data.get('id')
    messages = data.get('messages')
    try:
        user_id_obj = ObjectId(user_id)
        if conversation_id:
            # 更新已有对话记录
            history_collection.update_one(
                {'_id': ObjectId(conversation_id), 'user_id': user_id_obj},
                {'$set': {'messages': messages}}
            )
        else:
            # 插入新对话记录
            new_record = {'user_id': user_id_obj, 'messages': messages}
            result = history_collection.insert_one(new_record)
            conversation_id = str(result.inserted_id)
        return jsonify({'id': conversation_id}), 200
    except Exception as e:
        logging.error(f'更新历史记录失败: {str(e)}')
        return jsonify({'message': f'更新历史记录失败: {str(e)}'}), 500


# 删除历史记录接口
def delete_history(conversation_id):
    if 'user_id' not in session:
        return jsonify({'message': '用户未登录'}), 401
    user_id = session['user_id']
    try:
        user_id_obj = ObjectId(user_id)
        conversation_id_obj = ObjectId(conversation_id)  # 将 conversation_id 转换为 ObjectId
        logging.info(f'尝试删除对话，用户 ID: {user_id}，对话 ID: {conversation_id}')
        result = history_collection.delete_one(
            {'_id': conversation_id_obj, 'user_id': user_id_obj}
        )
        if result.deleted_count > 0:
            logging.info(f'对话删除成功，用户 ID: {user_id}，对话 ID: {conversation_id}')
            return jsonify({'message': '删除成功'}), 200
        else:
            logging.info(f'未找到对应对话，用户 ID: {user_id}，对话 ID: {conversation_id}')
            return jsonify({'message': '记录不存在或无权限删除'}), 404
    except Exception as e:
        logging.error(f'删除历史记录失败: {str(e)}，用户 ID: {user_id}，对话 ID: {conversation_id}')
        return jsonify({'message': f'删除历史记录失败: {str(e)}'}), 500

# 保存新对话
def save_conversation():
    if 'user_id' not in session:
        return jsonify({'message': '请先登录'}), 401
    data = request.get_json()
    history_collection.insert_one(data)
    return jsonify({'message': '对话保存成功'}), 201

# 更新对话
def update_conversation():
    if 'user_id' not in session:
        return jsonify({'message': '请先登录'}), 401
    data = request.get_json()
    history_collection.replace_one({'id': data['id']}, data)
    return jsonify({'message': '对话更新成功'})

# 删除对话
def delete_conversation(conversation_id):
    if 'user_id' not in session:
        return jsonify({'message': '请先登录'}), 401
    result = history_collection.delete_one({'id': conversation_id})
    if result.deleted_count > 0:
        return jsonify({'message': '对话删除成功'})
    else:
        return jsonify({'message': '未找到对应对话'}), 404